﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using DiffuseEnjoyIdle.Core.Extensions;
using DiffuseEnjoyIdle.Core.Helper;
using DiffuseEnjoyIdle.EntityFrameworkCore;
using DiffuseEnjoyIdle.Extension.Extensions;
using DiffuseEnjoyIdle.TimedTaskCentre.Quartz;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);


builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory(a =>
{
    a.RegisterModule(new AutofacModuleRegister());
})).ConfigureAppConfiguration((hostingContext, config) =>
{
    var rootPath = hostingContext.HostingEnvironment.ContentRootPath;
    var cfgPath = PathTool.GetConfigPath(rootPath);
    config.AddCommandLine(args)
            .AddCommandLine(new[] { $"{Path.GetDirectoryName(cfgPath)}" })
            .AddJsonFile(Path.Combine(cfgPath, "appsettings.json"), false, true)
            .AddApolloExtension();
});

var services = builder.Services;
var configuration = builder.Configuration;

services.AddDbContext<DBContext>(
       opt => opt.UseMySql(configuration.GetConnectionString("mysql"), ServerVersion.Parse("8.0.21-mysql"))
   );

builder.Services.AddQuartz(q =>
{
//支持DI，默认Ijob 实现不支持有参构造函数
q.UseMicrosoftDependencyInjectionJobFactory();


q.ScheduleJob<QuartzJob>(trigger => trigger
        .WithIdentity("ConnectionRemoteApiTrigger")
        .StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(7)))
        .WithDailyTimeIntervalSchedule(x => x.WithInterval( 10, IntervalUnit.Second))
        .WithDescription("定时访问远程接口")
    );


});
builder.Services.AddQuartzServer(options =>
{
// when shutting down we want jobs to complete gracefully
options.WaitForJobsToComplete = true;
});


builder.Services.AddTransient<QuartzJob>(); 

services.AddSingleton(p =>
{
    var connStr = configuration.GetConnectionString("redis");
    return ConnectionMultiplexer.Connect(connStr);
});



var app = builder.Build();

 

app.Run();
